package com.learn.demo.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 发送附件
 *
 * @author banjiawei
 * @date 2021/06/23
 */
@RestController
public class AttachFileMailController {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    @RequestMapping("/attach/sendAttachFileMail")
    public void sendAttachFileMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true, "utf-8");
        helper.setSubject("这是一封带附件的测试邮件");
        helper.setFrom(username);
        List<String> stringList = Arrays.asList("2221512643@qq.com", "331939299@qq.com");
        String[] strings = new String[stringList.size()];
        stringList.toArray(strings);
        helper.setTo(strings);
        //helper.setCc("37xxxxx37@qq.com");
        //helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());

        helper.setText("这是带附件测试邮件的正文");
        // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
        String filePath = "C:\\Users\\Administrator\\Desktop\\班佳伟简历（20210617）.docx";
        helper.addAttachment(MimeUtility.encodeText("班佳伟简历（20210617）.docx", StandardCharsets.UTF_8.name(), "B"), new File(filePath));
        javaMailSender.send(mimeMessage);
    }
}
